<?php

namespace App\Http\Controllers\ZHIHU\Systems;

use DB;
use Config;
use Carbon\Carbon;
use Illuminate\Support\Str;
use Overtrue\Pinyin\Pinyin;
use App\Http\Controllers\ZHIHU\ApiController;
use Illuminate\Http\Request;
use App\Eloqumd\Zhihu\ZhihuUser;
use App\Eloqumd\Zhihu\ZhihuQuestion;
use App\Eloqumd\Zhihu\ZhihuAnswer;
use App\Eloqumd\System\SysVisit;
use App\Eloqumd\Zhihu\ZhihuSystemAdv;
use App\Eloqumd\System\BrowseLog;
use App\Eloqumd\Zhihu\ZhihuReportAnswer;
use App\Eloqumd\Zhihu\ZhihuReportQuestion;
use App\Eloqumd\Zhihu\ZhihuTopic;

class WebInfomationCenterController extends ApiController
{
    // 站内用户
    static $systemWebUserRouteVerify = ['list', 'status'];

    // 站内用户--list=列表，status=启用禁用
    public function userManager(Request $request, $name)
    {
        if (!in_array($name, static::$systemWebUserRouteVerify)) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Router-Limited', ['name' => $name]), null, 'verror');
        }

        $param = $request->all();

        $method = "userManager" . Str::ucfirst($name) . "Operation";

        return $this->$method($param);
    }

    // 站内用户【列表】
    public function userManagerListOperation($input)
    {
        $page = (int)($input['page'] ?? 1);
        $limit = $input['limit'] ?? $this->limit;
        $offest = ($page - 1) * $limit;
        // 关键字
        $keyword = $input['keyword'] ?? '';

        $where = null;
        $where[] = ['user_type', '=', 1];
        // 快捷搜索
        if ($keyword) {
            $where[] = ['name', 'like', "%{$keyword}%", 'AND'];
            $where[] = ['nickname', 'like', "%{$keyword}%", 'OR'];
        }

        $totalCount = ZhihuUser::where($where)->count();
        $listData = ZhihuUser::where($where)
            ->offset($offest)
            ->limit($limit)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 站内用户【启用禁用】
    public function userManagerStatusOperation($input)
    {
        $id = $input['id'] ?? 0;
        $status = $input['status'] ?? '';
        if (!$id || $status == '' || !in_array($status, [0, 1])) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuUser::find($id);
            $model->status = $status;
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'status');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'status');
        }
    }

	public function getSystemRotate(Request $request)
	{
		$jsonData = [];
		// 用户注册量
		$userConut = ZhihuUser::where('status', 1)->where('user_type', 1)->count();
		$jsonData[] = [
			'count' => (int)$userConut,
			'title' => trans('zhihu.System-User-Count-Title'),
			'icon' => 'el-icon-s-custom',
			'color' => sprintf( "#%06X", mt_rand(0, 0xFFFFFF))
		];
        // 广告投放数
        $advsCount = ZhihuSystemAdv::where('status', 1)->count();
        $jsonData[] = [
        	'count' => (int)$advsCount,
        	'title' => trans('zhihu.System-Advs-Count-Title'),
        	'icon' => 'el-icon-goods',
        	'color' => sprintf( "#%06X", mt_rand(0, 0xFFFFFF))
        ];
        // 问题数
        $questionCount = ZhihuQuestion::where('status', 1)->count();
        $jsonData[] = [
        	'count' => (int)$questionCount,
        	'title' => trans('zhihu.System-Question-Count-Title'),
        	'icon' => 'el-icon-question',
        	'color' => sprintf( "#%06X", mt_rand(0, 0xFFFFFF))
        ];
        // 评论数
        $commentCount = ZhihuAnswer::where('status', 1)->count();
        $jsonData[] = [
        	'count' => (int)$commentCount,
        	'title' => trans('zhihu.System-Comment-Count-Title'),
        	'icon' => 'el-icon-chat-line-round',
        	'color' => sprintf( "#%06X", mt_rand(0, 0xFFFFFF))
        ];
        // 访客数-访问量
        $sysVisit = SysVisit::where('puv', 'zhihu')->first();
        $jsonData[] = [
        	'count' => (int)$sysVisit->uv,
        	'title' => trans('zhihu.System-Uv-Count-Title'),
        	'icon' => 'el-icon-user-solid',
        	'color' => sprintf( "#%06X", mt_rand(0, 0xFFFFFF))
        ];
        $jsonData[] = [
        	'count' => (int)$sysVisit->pv,
        	'title' => trans('zhihu.System-Pv-Count-Title'),
        	'icon' => 'el-icon-view',
        	'color' => sprintf( "#%06X", mt_rand(0, 0xFFFFFF))
        ];
        // 问题/评论举报数
        $aswCount = ZhihuReportAnswer::count();
        $qusCount = ZhihuReportQuestion::count();
        $jsonData[] = [
        	'count' => (int)$aswCount + (int)$qusCount,
        	'title' => trans('zhihu.System-Report-Count-Title'),
        	'icon' => 'el-icon-s-flag',
        	'color' => sprintf( "#%06X", mt_rand(0, 0xFFFFFF))
        ];
        // 日志记录数
        $logsCount = BrowseLog::where('log_k', 'zhihu')->count();
        $jsonData[] = [
        	'count' => (int)$logsCount,
        	'title' => trans('zhihu.System-Logs-Count-Title'),
        	'icon' => 'el-icon-warning',
        	'color' => sprintf( "#%06X", mt_rand(0, 0xFFFFFF))
        ];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'total');
	}

    public function getSystemTabs(Request $request)
	{
		$jsonData = [];
        $pinyin = new Pinyin();
        $topicData = ZhihuTopic::where('status', 1)->get();
        foreach ($topicData as $k => $v) {
            $key = substr(strtoupper($pinyin->abbr($v->name, null)), 0, 1);
            $jsonData[] = [
                'title' => $v->name,
                'subtitle' => trans('zhihu.System-Topic-Total-Sub-Title'),
                'count' => (int)$v->questions_count,
                'allcount' => (int)$v->followers_count,
                'text' => trans('zhihu.System-Topic-Followers-Title'),
                'color' => sprintf( "#%06X", mt_rand(0, 0xFFFFFF)),
                'key' => $key == '' ? strtoupper(substr($v->name, 0, 1)) : $key
            ];
        }

        return $this->jsonReturns(10000, $this->success, $jsonData, 'total');
    }

    public function getSystemCard(Request $request)
    {
        $data = BrowseLog::select(DB::raw('count(log_user_id) as nums'), 'log_user_id')->where('log_k', 'zhihu')->groupBy('log_user_id')->orderBy(DB::raw('count(log_user_id)'), 'desc')->offset(0)->limit(4)->get();

        $total = BrowseLog::where('log_k', 'zhihu')->count();

        $jsonData = [];
        $progressData = [];
        $emptyDesc = trans('zhihu.Empty-User-Desc');
        foreach ($data as $k => $v) {
            $user = ZhihuUser::find($v->log_user_id);
            if (is_null($user)) continue;
            $jsonData[] = [
                'name' => $user->nickname,
                'src' => empty($user['avatar']) ? Config::get('api.zhihu_default_img') : $user['avatar'],
                'text' => (is_null($user->settings) ? $emptyDesc : (isset($user->settings['intro']) && !empty($user->settings['intro']) ? $user->settings['intro'] : $emptyDesc)),
            ];
            $progressData[] = [
                'title' => trans('zhihu.System-Activity_Progress-Title'),
                'color' => sprintf( "#%06X", mt_rand(0, 0xFFFFFF)),
                'count' => round(($v['nums'] / $total) * 100)
            ];
        }

        $finalData['card'] = $jsonData;
        $finalData['progress'] = $progressData;

        return $this->jsonReturns(10000, $this->success, $finalData, 'total');
    }

    public function getSystemHotQuestion(Request $request)
    {
        $jsonData = [];
        $jsonData = ZhihuQuestion::where('status', 1)
            ->orderBy('favourite_count', 'desc')
            ->orderBy('answers_count', 'desc')
            ->orderBy('followers_count', 'desc')
            ->orderBy('read_count', 'desc')
            ->offset(0)
            ->limit(10)
            ->get()
            ->toArray();
        foreach ($jsonData as $k => $v) {
            $topic = ZhihuTopic::find($v['topic_id']);
            $user = ZhihuUser::find($v['user_id']);
            $cate = Config::get('api.zhihu_question_type')[$v['cates']];
            $jsonData[$k]['catesShow'] = $cate;
            $jsonData[$k]['topic'] = $topic->name;
            $jsonData[$k]['publishname'] = $user->nickname;
            $jsonData[$k]['fclr'] = $v['favourite_count'] . ' / ' . $v['answers_count'] . ' / ' . $v['followers_count'] . ' / ' . $v['read_count'];
        }

        return $this->jsonReturns(10000, $this->success, $jsonData, 'total');
    }
}
